/**
 * UserController
 *
 * @description :: Server-side logic for managing Users
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var userObject = {
	username: {
		pattern: /(^[a-zA-Z]\w{3,15}$)|(^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8]))\d{8}$)/
	},
	password: {
		pattern: /^[a-zA-Z]\w{3,15}$/
	},

};

var uuid = require("node-uuid");

var vcode = 123456;

module.exports = {

	create: function(req, res){
		
		var params = req.params.all();
		var err = [];

		for(var i in userObject) {

			var t = params[i];
			if(!t) {
				err.push(t);
				continue;
			}

			if(!userObject[i].pattern.test(t)) {
				err.push(t);
				continue;
			}

		}

		if(err.length > 0) {

			return res.json({
				code: -1,
				error: err
			});

		}

		var username = params.username;
		var password = params.password;
		var salt = uuid.v4();

		HashService.hash(password, salt, function(err, data){
			
			if(err) {
				return res.json({
					code: -1,
					message: "注册失败"
				});
			}

			var password =  data.toString();
			User.create({ username:username, password: password, salt:salt }).exec(function(err, user){
				if(err) {
					return res.json({
						code: -1,
						message: "注册失败"
					});
				}
				return res.json({
					code: 0,
					ok: true,
					id: user.id,
					username:user.username,
					token: user.token
				});

			});

			

		});

	},


	check: function(req, res){

		var username = req.params.all().username;

		if(!username || !userObject.username.pattern.test(username)) {
			return res.json({
				code: -1,
				message: "用户名必须字母开头"
			});
		}

		User.findOne({
			username:username
		}).exec(function(err, user){

			if(user!=null)
				return res.json({
					code: 0,
					ok: false,
					message: "用户名已被注册"
				});

			return res.json({
				code: 0,
				ok: true,
				message: "用户名可以注册"
			});

		});

	},

	getVcode: function(req, res){

		var mobile = req.params.all().mobile;
		
		if(!mobile) {
			return res.json({
				code: -1,
				ok: false,
				message: "手机号码错误"
			});
		}

		return res.json({
			code: 0,
			ok: true,
			vcode: vcode
		});


	},

	checkVcode: function(req, res){
	
		var mobile = req.params.all().mobile;
		var _vcode = req.params.all().vcode;
		
		if(!mobile) {
			return res.json({
				code: -1,
				ok: false,
				message: "手机号码错误"
			});
		}
		
		if(!vcode || _vcode != vcode) {

			return res.json({
				code: -1,
				ok: false,
				message: "验证那错误"
			});

		}

		return res.json({
			code: 0,
			ok: true,
		});



	},

};

